//
//  vspOperation.m
//  妙居
//
//  Created by gaogao on 19/07/2017.
//  Copyright © 2017 miotlink. All rights reserved.
//

#import "vspOperation.h"
#import "vspConnect.h"
#import "MMWMiotLink.h"
#import "vspProtocol.h"

@interface vspOperation ()<vspConnectDelegate>
{
    vspSuccessBlock _success;
    vspFailureBlock _failure;

    BOOL _isReceiveHeartData;
    int cuid;
    NSNumber *sendCuid;
    int timeout;
    int ipv6Port;
    NSString *receiveIpStr;
    dispatch_source_t _heardTimer;
    dispatch_source_t _checkTimer;

}
@property(nonatomic,strong)NSMutableDictionary *cmsDomainNameDic;
@property(nonatomic,strong)NSString *cmsDomainName;
@end

@implementation vspOperation

+ (instancetype)shareInstance
{
    static vspOperation *once = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        once = [[vspOperation alloc] init];
    });
    return once;
}

-(void)connectDeviceGetIp:(NSString*)ip
                     port:(int)port
                  success:(vspSuccessBlock)success
                  failure:(vspFailureBlock)failure
{
    
    [vspConnect shareInstance].delegate = self;
    
    [[vspConnect shareInstance] getSocket:ip onPort:port];
    _success = success;
    _failure = failure;
}

- (void)sendCommand:(NSString*)command
{
    NSData *data = [MMWMiotLink encodeDataWithCommand:command];
    [[vspConnect shareInstance].socket writeData:data withTimeout:10 tag:200];
}
#pragma mark vspConnectDelegate
- (void)receiveSocketData:(NSData *)data
{
    NSLog(@"接收到指令:%@",data);
    NSDictionary *ttdataDic = [vspProtocol decodeTTData:data];
//    NSDictionary *dataDic = [MMWMiotLink decodeDeviceData:data];
    NSNotification *notification =[NSNotification notificationWithName:@"deviceData" object:nil userInfo:ttdataDic];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}

- (void)didConnectToHost
{
    _success();
}
- (void)failAction:(NSError *)err
{
    _failure(err);
}

#pragma mark methods

- (void)activedisconnect
{
    [[vspConnect shareInstance] closeSocket];
    
}

@end

